import 'dart:convert';
import 'dart:io';

/**
 * GET请求
 * @param host 请求域名
 * @param path 请求路径
 * @param params 请求参数
 */
fetchGet(host, path, [params]) async {
  var httpClient = HttpClient();
  var uri = Uri.http(host, path, params != null ? params : {});
  var req = await httpClient.getUrl(uri);
  var res = await req.close();
  if (res.statusCode == HttpStatus.ok) {
    var json = await res.transform(utf8.decoder).join();
    return jsonDecode(json);
  } else {
    throw Exception("请求失败");
  }
}

/**
 * POST请求
 * @param url 请求路径
 * @param params 请求参数
 */
fetchPost(url, [params]) async {
  var httpClient = HttpClient();
  var req = await httpClient.postUrl(Uri.parse(url));
  req.headers.set("content-type", "application/json");
  req.add(utf8.encode(json.encode(params != null ? params : {}))); 
  var res = await req.close();
  if (res.statusCode == HttpStatus.ok) {
    var json = await res.transform(utf8.decoder).join();
    return jsonDecode(json);
  } else {
    throw Exception("请求失败");
  }
}

// 入口主函数
void main() {
  (() async {
    var result = await fetchGet("xzserver.applinzi.com", "/index");
    (result as List).forEach((element) => print(element));

    print("=================");

    result = await fetchGet("xzserver.applinzi.com", "/details", { "lid": "5" });
    print(result);

    print("=================");

    result = await fetchPost("http://xzserver.applinzi.com/users/signin", { "uname": "dingding", "upwd": "123456" });
    print(result);

  }());
}
